<?php

    /**
    * This is the model class for table "post".
    *
    * The followings are the available columns in table 'post':
    * @property string $id
    * @property string $title
    * @property string $alias
    * @property string $content
    * @property string $cat_parent_id
    * @property string $cat_id
    * @property integer $is_all_city
    * @property integer $city_id
    * @property string $district_id
    * @property string $address
    * @property string $latlng
    * @property integer $show_map
    * @property string $user_id
    * @property string $price
    * @property string $image
    * @property string $image_count
    * @property string $state
    * @property string $status
    * @property string $type
    * @property integer $area_use
    * @property integer $area_floor
    * @property integer $view_count
    * @property integer $reply_count
    * @property integer $image_count
    * @property string $created
    * @property string $changed
    * @property string $upped
    * @property string $indexed
    * 
    * The followings are the available model relations:
    * @property Cat $cat
    * @property PostImage[] $postImages
    * @property PostReply[] $postReplies
    * @property UserFollowPost[] $userFollowPosts
    * @property UserFollowUserAction[] $userFollowUserActions
    * @property UserLikePost[] $userLikePosts
    */
    class Post extends CActiveRecord
    {

        public $price_from;
        public $price_to;
        public $area_use_about;
        public $area_floor_about;
        public $sort = 'cap-nhat-moi';
        public $has_image;
        public $keyword;
        public $cat_alias;
        public $city_alias;
        public $district_alias;

        /**
        * Returns the static model of the specified AR class.
        * @param string $className active record class name.
        * @return Post the static model class
        */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }

        /**
        * @return string the associated database table name
        */
        public function tableName()
        {
            return 'post';
        }

        /**
        * @return array validation rules for model attributes.
        */
        public function rules()
        {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(
                array('title, alias, content, user_id, status', 'required'),
                array('cat_parent_id, cat_id', 'required', 'message' => '{attribute} phải được chọn'),
                array('city_id, district_id, image_count', 'numerical', 'integerOnly'=>true),
                array('title', 'length', 'max'=>70),
                array('title, alias, address, latlng, price_from, price_to, area_use_about, area_floor_about, sort, keyword, city_alias, cat_alias, district_alias', 'length', 'max'=>255),
                array('is_all_city, cat_id, cat_parent_id, city_id, district_id, user_id, price, show_map, area_use, area_floor, has_image', 'length', 'max'=>255),
                array('desc', 'length', 'max'=>500),
                array('image', 'length', 'max'=>300),
                array('state, type, status', 'length', 'max'=>200),
                array('changed, created, upped', 'safe'),

                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('id, title, alias, content, cat_id, city_id, district_id, address, latlng, show_map, user_id, price, image, state, status, type, area_use, area_floor, created, changed, upped', 'safe', 'on'=>'search'),
            );
        }

        /**
        * @return array relational rules.
        */
        public function relations()
        {
            // NOTE: you may need to adjust the relation name and the related
            // class name for the relations automatically generated below.
            return array(
                'city' => array(self::BELONGS_TO, 'City', 'city_id'),
                'district' => array(self::BELONGS_TO, 'District', 'district_id'),
                'cat' => array(self::BELONGS_TO, 'PostCat', 'cat_id'),
                'catParent' => array(self::BELONGS_TO, 'PostCat', 'cat_parent_id'),
                'postImages' => array(self::HAS_MANY, 'PostImage', 'post_id', 'condition' => "reply_id IS NULL"),
                'postReplies' => array(self::HAS_MANY, 'PostReply', 'post_id'),
                'userFollowPosts' => array(self::HAS_MANY, 'UserFollowPost', 'post_id'),
                'userFollowUserActions' => array(self::HAS_MANY, 'UserFollowUserAction', 'post_id'),
                'userLikePosts' => array(self::HAS_MANY, 'UserLikePost', 'post_id'),
                'user' => array(self::BELONGS_TO, 'User', 'user_id'),
            );
        }

        /**
        * @return array customized attribute labels (name=>label)
        */
        public function attributeLabels()
        {
            return array(
                'id' => 'ID',
                'title' => 'Tiêu đề',
                'alias' => 'SEO url',
                'desc' => 'SEO description',
                'content' => 'Nội dung',
                'cat_parent_id' => 'Nhóm chuyên mục ',
                'cat_id' => 'Chuyên mục',
                'cat_alias' => 'Chuyên mục',
                'city_id' => 'Thành phố',
                'city_alias' => 'Thành phố',
                'district_id' => 'Quận',
                'district_alias' => 'Quận',
                'address' => 'Địa chỉ',
                'latlng' => 'Tọa độ',
                'show_map' => 'Hiện bản đồ trong bài',
                'user_id' => 'User',
                'price' => 'Giá',
                'price_from' => 'Giá từ',
                'price_to' => 'Giá đến',
                'image' => 'Ảnh',
                'state' => 'Tình trạng',
                'status' => 'Trạng thái bài',
                'type' => 'Loại tin',
                'area' => 'Diện tích',
                'area_use' => 'DT sử dụng',
                'area_use_about' => 'DT sử dụng',
                'area_floor' => 'DT mặt bằng',
                'area_floor_about' => 'DT mặt bằng',
                'created' => 'Created',
                'changed' => 'Changed',
                'upped' => 'Thời gian UP',
                'is_all_city' => 'Toàn quốc',
                'has_image' => 'Có ảnh',
                'keyword' => 'Tìm kiếm',
            );
        }

        public function getModel($id, $condition=''){
            $model = $this->findByPk($id, $condition);
            if(!$model) throw new CHttpException(404, 'Bài viết không tồn tại');
            return $model;
        }

        public function checkUserPermisstion($postId = null){
            $user = Yii::app()->user->user;
            if(!$user) return false;

            $userInfo = Yii::app()->user->userInfo;
            if($userInfo && $userInfo->isMod) return true;

            $postId = $postId ? $postId : $this->id;
            return Post::model()->exists('id = :id AND user_id = :user_id', array(':id' => $postId, ':user_id' => $user->id));
        }


        public function filterAttributes(){
            $purifier=new CHtmlPurifier();
            $purifier->options = array(
                //                'HTML.AllowedAttributes' => 'a.rel, a.href, a.target, img.src, *.title, *.style',
                'Attr.AllowedRel' => array('nofollow'),
                'HTML.TargetBlank' => true,
            );
            $this->title = $purifier->purify($this->title);    
            $this->content = strip_tags($this->content, '<strong><em><u><del><p><br><div><span><a><img><ul><o><li>');
            $this->content = $purifier->purify($this->content);    
            $this->content = preg_replace(array(
                '{[\n\s]+}', 
                '{(\s*(<\s*br\s*/?\s*>)\s*){3,}}'
                ), array(
                    ' ',
                    '<br /><br />'
                ), $this->content);

            $rows = explode('<br />', $this->content);
            $rows2 = array();
            foreach($rows as $row){
                //http://www.asciitable.com/
                //echo '<pre>';print_r(ord($row));echo '</pre>';
                if(ord($row) < 176)  
                    $rows2[] = trim($row);
            }
            $this->content = implode("\n", $rows2);
            $this->content = trim($this->content);
            $this->content = str_replace("\n", '<br />', $this->content);

            $this->desc = Myext::char_limiter(strip_tags($this->content, '<br>'), 200);
            $this->desc = preg_replace('{(\s*(<\s*br\s*/?\s*>)\s*){3,}}', '<br /><br />', $this->desc);

            $this->price = is_numeric($this->price) ? $this->price : null;
            $this->area_floor = is_numeric($this->area_floor) ? $this->area_floor : null;
            $this->area_use = is_numeric($this->area_use) ? $this->area_use : null;
        }

        public function beforeSave(){
            return parent::beforeSave();
        }

        public function afterSave(){
            return parent::afterSave();
        }

        public function getFolderNum($id = NULL){
            $id = $id ? $id : $this->id;
            for($i = 1000; $i < 100000000; $i += 1000){
                if($id <= $i) return $i;   
            }   
        }

        public function getImagePath($id = NULL){
            $id = $id ? $id : $this->id;
            $folder = $this->getFolderNum($id);
            return Yii::app()->params->hangve['post']['path']."{$folder}/{$id}/"; 
        }  

        public function getImageUrl($size = 'small', $id = null, $image = null){
            $id = $id ? $id : $this->id;
            $image = $image ? $image : $this->image;
            return "/".$this->getImagePath($id)."{$image}_{$size}.jpg";
        }

        /**
        * Chỉ dành cho ảnh square 50, 100, 150
        */
        public function getImageSquareDetect($size = '150', $id = null, $image = false, $user_id = null){
            $image = $image !== false ? $image : $this->image;
            $noImage = "/files/img/no_item/item_{$size}.jpg";
            if($image){
                return $this->getImageUrl('square_'.$size, $id, $image);    
            }else{
                return User::model()->getAvatarUrl($size, $user_id, false, $noImage);
            }
        }  

        public function getSortData(){
            return array(
                'cap-nhat-moi' => 'Cập nhật mới',
                'chu-de-moi' => 'Chủ đề mới',
                //'tra-loi-nhieu' => 'Trả lời nhiều',
                're-nhat' => 'Rẻ nhất',
                //'xem-nhieu-nhat' => 'Xem nhiều nhất',
                //'xem-nhieu-trong-thang' => 'Xem nhiều trong tháng',
            );
        }

        public function getSortMapping(){
            return array(
                'cap-nhat-moi' => 'upped',
                'chu-de-moi' => 'created',
                //'tra-loi-nhieu' => 'reply_count',
                're-nhat' => 'price',
                //'xem-nhieu-nhat' => 'view_count',
                //'xem-nhieu-trong-thang' => 'view_count_month',
            );
        }


        public function getStateData(){
            return array(
                'moi' => 'Mới 100%',
                'gan-nhu-moi' => 'Gần như mới',
                'cu' => 'Cũ',
            );
        }
        public function getStateLabel(){
            return $this->state ? $this->stateData[$this->state] : null;
        }



        public function getStatusData($isDisable = true){
            $data = array(
                'dang-ban' => 'Đang bán',
                'da-ban' => 'Đã bán, ngừng thảo luận',
            );
            if($isDisable){
                $data['cho-duyet'] = 'Chờ duyệt';    
                $data['khoa'] = 'Khóa';    
            }
            return $data;
        }
        public function getStatusLabel(){
            return $this->statusData[$this->status];
        }

        public function getTypeData($isRent = true){
            $data = array(
                'mua' => 'Mua',
                'ban' => 'Bán',
            );
            if($isRent){
                $data['thue'] = 'Thuê';    
                $data['cho-thue'] = 'Cho thuê';    
            }
            return $data;
        }


        public function getTypeLabel(){
            return $this->type ? $this->typeData[$this->type] : null;
        }

        public function getPriceData(){
            return array(
                '50000' => '50 nghìn',
                '100000' => '100 nghìn',
                '200000' => '200 nghìn',
                '300000' => '300 nghìn',
                '500000' => '500 nghìn',
                '700000' => '700 nghìn',
                '1000000' => '1 triệu',
                '2000000' => '2 triệu',
                '3000000' => '3 triệu',
                '5000000' => '5 triệu',
                '7000000' => '7 triệu',
                '10000000' => '10 triệu',
                '12000000' => '12 triệu',
                '15000000' => '15 triệu',
                '17000000' => '17 triệu',
                '20000000' => '20 triệu',
                '30000000' => '30 triệu',
                '50000000' => '50 triệu',
                '70000000' => '70 triệu',
                '100000000' => '100 triệu',
                '200000000' => '200 triệu',
                '300000000' => '300 triệu',
                '500000000' => '500 triệu',
                '700000000' => '700 triệu',
                '1000000000' => '1 tỷ',
                '2000000000' => '2 tỷ',
                '3000000000' => '3 tỷ',
                '4000000000' => '4 tỷ',
                '5000000000' => '5 tỷ',
            );
        } 

        public function getAreaAboutData(){
            return array(
                'nho-hon-30-m2' => '< 30 m2',
                '30-60-m2' => '30-60 m2',
                '60-100-m2' => '60-100 m2',
                '100-150-m2' => '100-150 m2',
                '150-200-m2' => '150-200 m2',
                '200-300-m2' => '200-300 m2',
                '300-500-m2' => '300-500 m2',
                'lon-hon-500-m2' => '> 500 m2',
            );
        }

        public function getAreaAboutFromTo($key){
            $key = str_replace('-m2', '', $key);
            if(strpos($key, 'nho-hon-') !== false){
                return array(1, str_replace('nho-hon-', '', $key));
            }
            if(strpos($key, 'lon-hon-') !== false){
                return array(str_replace('lon-hon-', '', $key), 1000000000);
            }
            return explode('-', $key);      
        }

        /**
        * Tìm vị trí của key là thứ mấy. 
        * 
        * @param mixed $key
        */
        public function getAreaAboutKeyIndex($key){
            $keyData = array_keys($this->areaAboutData);
            return array_search($key, $keyData);  
        }


        public function getUrl($action = 'view', $id = null, $alias = null){
            if(in_array($action, array('create', 'createShop'))){
                return Yii::app()->createAbsoluteUrl('/hangve/post/'.$action);
            }

            $id = $id ? $id : $this->id;
            $alias = $alias ? str_replace(' ', '-', $alias) : $this->alias;
            return Yii::app()->createAbsoluteUrl('/hangve/post/'.$action, array('id' => $id, 'alias' => $alias));
        }

        public function getPriceFormat($price = null){
            $price = $price ? $price : $this->price;
            if(!$price) return null;
            return number_format($price, 0, ',', '.');
        }

        public function getPriceLabel($price = null){
            $price = $price ? $price : $this->price;
            if(!$price) return null;
            return $this->getPriceFormat($price).'₫';
        }

        public function getAreaUseFormat(){
            if(!$this->area_use) return null;
            return number_format($this->area_use, 0, ',', '.');
        }
        public function getAreaUseLabel(){
            if(!$this->area_use) return null;
            return $this->areaUseFormat.' m<sup>2</sup>';
        }

        public function getAreaFloorFormat(){
            if(!$this->area_floor) return null;
            return number_format($this->area_floor, 0, ',', '.');
        }
        public function getAreaFloorLabel(){
            if(!$this->area_floor) return null;
            return $this->areaFloorFormat.' m<sup>2</sup>';
        }


        public function getViewCountLabel(){
            return number_format($this->view_count, 0, ',', '.');
        }
        public function getAddressFull(){
            $array = array();
            if($this->address) $array[] = $this->address;
            if($this->district) $array[] = $this->district->name;
            if($this->city) $array[] = $this->city->name;
            return implode(', ', $array);
        }


        public function getDescStrip(){
            return preg_replace('{(\s*(<\s*br\s*/?\s*>)\s*){3,}}', ' ', $this->desc);
        }

        public function updateReplyCount($id = null){
            $id = $id ? $id : $this->id;
            $query = "UPDATE post p SET reply_count = (SELECT COUNT(*) FROM post_reply WHERE post_id = p.id) 
            WHERE id = {$id};";   
            Yii::app()->db->createCommand($query)->execute();
        }

        public function updateImageCount($postId = null){
            $postId = $postId ? $postId : $this->id;
            $query = "UPDATE post p SET image_count = (SELECT COUNT(*) FROM post_image WHERE post_id = p.id)
            WHERE id = {$postId};";    
            Yii::app()->db->createCommand($query)->execute();
        }

        /**
        * Lấy Reply cuối của bài viết
        * @return PostReply
        */
        private $_replyLast = false;
        public function getReplyLast(){
            if($this->_replyLast !== false) return $this->_replyLast;

            return $this->_replyLast = PostReply::model()->findByAttributes(array(
                'post_id' => $this->id
                ), array(
                    'limit' => 1,
                    'order' => 'created DESC'
            ));
        }

        public function getElasticClient(){
            require APP_PATH.'/vendor/autoload.php';
            $clientParams = array(
                'hosts' => array(
                    '192.241.226.222:7641',         // IP + Port
                    //'192.241.226.222',              // Just IP
                    //'giatlavui.com:7641', // Domain + Port
                    //'giatlavui.com'      // Just Domain
                ),
                //                'connectionParams' => array(
                //                    'auth' => array(
                //                        'elasticsearch',
                //                        '7641',
                //                        'Basic' 
                //                    )
                //                )
            );
            return new Elasticsearch\Client($clientParams);   
        }

        public function elasticsearchCreate(){
            $client = Post::model()->elasticClient;
            $index = IS_LOCAL ? 'hangve_local' : 'hangve';
            $indexParams = array(
                'index' => $index, 
                'body' => array(
                    'settings' => array(
                        'number_of_shards' => 1,
                        'number_of_replicas' => 0,
                        //'refresh_interval' => -1,
                        //                        'analysis' => array(
                        //                            'analyzer' => array(
                        //                                'tokenizer' => 'standard',
                        //                                'filter' => array("lowercase"),
                        //                            )
                        //                        ),
                    ),
                    'mappings' => array(
                        'post' => array(
                            '_source' => array(
                                'enabled' => true
                            ),
                            'properties' => array(
                                'id'                =>  array('type' => 'integer',  'store' => 'yes'),
                                'title'             =>  array('type' => 'string',   'store' => 'yes',   'index' => 'analyzed'),
                                'title_unsigned'    =>  array('type' => 'string',   'store' => 'yes',   'index' => 'analyzed'),
                                'desc'              =>  array('type' => 'string',   'store' => 'yes',   'index' => 'no',),

                                'cat_parent_alias'  =>  array('type' => 'string',   'store' => 'yes',   'index' => 'not_analyzed'),
                                'cat_alias'         =>  array('type' => 'string',   'store' => 'yes',   'index' => 'not_analyzed'),
                                'city_alias'        =>  array('type' => 'string',   'store' => 'yes',   'index' => 'not_analyzed'),
                                'district_alias'    =>  array('type' => 'string',   'store' => 'yes',   'index' => 'not_analyzed'),

                                'address'           =>  array('type' => 'string',   'store' => 'yes',   'index' => 'no'),
                                'latlng'            =>  array('type' => 'geo_point','store' => 'yes',   'lat_lon' => true),

                                'type'              =>  array('type' => 'string',   'store' => 'yes',   'index' => 'not_analyzed'),
                                'state'             =>  array('type' => 'string',   'store' => 'yes',   'index' => 'not_analyzed'),
                                'status'            =>  array('type' => 'string',   'store' => 'yes',   'index' => 'not_analyzed'),

                                'area_use'          =>  array('type' => 'integer',  'store' => 'yes'),
                                'area_floor'        =>  array('type' => 'integer',  'store' => 'yes'),
                                'price'             =>  array('type' => 'long',     'store' => 'yes'),

                                'image'             =>  array('type' => 'string',   'store' => 'yes',   'index' => 'no'),
                                'has_image'         =>  array('type' => 'boolean',  'store' => 'yes'),
                                'image_count'       =>  array('type' => 'integer',  'store' => 'yes'),
                                'is_all_city'       =>  array('type' => 'boolean',  'store' => 'yes'),
                                'show_map'          =>  array('type' => 'boolean',  'store' => 'yes'),
                                'view_count'        =>  array('type' => 'integer',  'store' => 'yes'),
                                'view_count_month'  =>  array('type' => 'integer',  'store' => 'yes'),
                                'reply_count'       =>  array('type' => 'integer',  'store' => 'yes'),
                                'reply_last'        =>  array('type' => 'object',   'properties' => array(
                                    'id'                =>  array('type' => 'integer',  'store' => 'yes',   'index' => 'no'),
                                    'desc'              =>  array('type' => 'string',   'store' => 'yes',   'index' => 'no'),
                                    'created'           =>  array('type' => 'date',     'store' => 'yes',   'index' => 'no',  'format' => 'YYYY-MM-dd HH:mm:ss'),
                                    'user'              =>  array('type' => 'object',   'properties' => array(
                                        'id'                =>  array('type' => 'integer',  'store' => 'yes',   'index' => 'no'),
                                        'name'              =>  array('type' => 'string',   'store' => 'yes',   'index' => 'no'),
                                        'image'             =>  array('type' => 'string',   'store' => 'yes',   'index' => 'no'),
                                    )),
                                )),
                                'user'              =>  array('type' => 'object',   'properties' => array(
                                    'id'                =>  array('type' => 'integer',  'store' => 'yes',   'index' => 'no'),
                                    'name'              =>  array('type' => 'string',   'store' => 'yes',   'index' => 'no'),
                                    'image'             =>  array('type' => 'string',   'store' => 'yes',   'index' => 'no'),
                                )),
                                'upped'             =>  array('type' => 'date',     'store' => 'yes',   'format' => 'YYYY-MM-dd HH:mm:ss'),
                                'created'           =>  array('type' => 'date',     'store' => 'yes',   'format' => 'YYYY-MM-dd HH:mm:ss'),
                                'changed'           =>  array('type' => 'date',     'store' => 'yes',   'format' => 'YYYY-MM-dd HH:mm:ss', 'index' => 'no'),
                            )                                                                                     
                        )
                    )
                ),
            );    

            $client->indices()->create($indexParams);
//            $return = $client->indices()->create($indexParams);
//            echo '<pre>';print_r($return);echo '</pre>';die;
        }


        public function elasticsearchIndex($posts = array()){   
            //ini_set('max_execution_time', 300); 
            if($posts == 'all'){ 
                $this->elasticsearchCreate();
                $posts = Post::model()->findAll('`status` IN ("dang-ban","da-ban")');    
            }
            if(is_numeric($posts)){
                $posts = $this->getModel($posts);
            }
            $posts = !$posts ? array($this) : (is_array($posts) ? $posts : array($posts)); 

            $client = Post::model()->elasticClient;

            $index = IS_LOCAL ? 'hangve_local' : 'hangve';

//            $retType = $client->indices()->getMapping(array(
//                'index' => $index,
//                'type'  => 'post'
//            ));
//            echo '<pre>';print_r($retType);echo '</pre>';die;


            $indexingParams = array(
                'index' => $index,
                'type'  => 'post'
            );

            foreach($posts as $post){
                $cat_parent_alias = PostCat::model()->getParentAliasById($post->cat_parent_id);
                $cat_alias = PostCat::model()->getChildAliasById($cat_parent_alias, $post->cat_id);

                $city_alias = City::model()->getAliasById($post->city_id);
                $district_alias = City::model()->getDistrictAliasById($city_alias, $post->district_id);  

                $indexingParams['id']  = $post->id;

                $indexingParams['body']  = array(
                    'id'                =>  $post->id,
                    'title'             =>  $post->title,
                    'title_unsigned'    =>  str_replace('-', ' ', $post->alias),
                    'desc'              =>  $post->desc,

                    'cat_parent_alias'  =>  $cat_parent_alias,
                    'cat_alias'         =>  $cat_alias,
                    'city_alias'        =>  $city_alias,
                    'district_alias'    =>  $district_alias,

                    'address'           =>  $post->address,
                    'latlng'            =>  $post->latlng,
                    'type'              =>  $post->type,
                    'state'             =>  $post->state,
                    'area_use'          =>  $post->area_use,
                    'area_floor'        =>  $post->area_floor,
                    'price'             =>  $post->price,
                    'status'            =>  $post->status,
                    'image'             =>  $post->image,
                    'has_image'         =>  $post->image_count ? true : false,
                    'image_count'       =>  $post->image_count,
                    'is_all_city'       =>  $post->is_all_city ? true : false,
                    'show_map'          =>  $post->show_map ? true : false,
                    'view_count'        =>  $post->view_count,
                    'view_count_month'  =>  $post->view_count_month,
                    'reply_count'       =>  $post->reply_count,
                    'reply_last'        =>  array(
                        'id'                =>  $post->replyLast ? $post->replyLast->id : null,
                        'desc'              =>  $post->replyLast ? $post->replyLast->desc  : null,
                        'created'           =>  $post->replyLast ? $post->replyLast->created : null,
                        'user'          =>  array(
                            'id' => !empty($post->replyLast->user->id) ? $post->replyLast->user->id : null,
                            'name' => !empty($post->replyLast->user->name) ? $post->replyLast->user->name : null,
                            'image' => !empty($post->replyLast->user->image) ? $post->replyLast->user->image : null,
                        ),
                    ),
                    'user'       =>  array(
                        'id' => !empty($post->user->id) ? $post->user->id : null,    
                        'name' => !empty($post->user->name) ? $post->user->name : null,   
                        'image' => !empty($post->user->image) ? $post->user->image : null,   
                    ),
                    'upped'         =>  $post->upped,
                    'created'       =>  $post->created,
                    'changed'       =>  $post->changed,
                );
//                echo '<pre>';print_r($indexingParams);echo '</pre>';die;

                $ret = $client->index($indexingParams); // Document will be indexed to hangve/post/$id
//                echo '<pre>';print_r($ret);echo '</pre>';die;
                Post::model()->updateByPk($post->id, array('indexed' => MyDateTime::getCurrentTime()));
            } 

            return true;
        }


        /**
        * put your comment there...
        * 
        * @param mixed $post_id post_id or all
        */
        public function elasticsearchDelete($post_id = null){
            $post_id = $post_id ? $post_id : $this->id;
            $client = Post::model()->elasticClient;

            $index = IS_LOCAL ? 'hangve_local' : 'hangve';

            $deleteParams = array();
            $deleteParams['index'] = $index;
            $deleteParams['type'] = 'post';
            if($post_id != 'all' && is_int($post_id)){
                $deleteParams['id'] = $post_id;    
            }
            $retDelete = $client->delete($deleteParams);
        }
    }

